package sisi;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.zkoss.zk.ui.Sessions;

/**
 * MyEmf.java - Emf class controller. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 23/09/2013
 * 
 */

public class MyEmf {

	private EntityManagerFactory emf;
	private String _utente, _password;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public EntityManagerFactory getEmf() {

		// Global emf
		if (emf == null || !emf.isOpen()) {
			Properties prop = new Properties();
			try {
				prop.load(getClass().getResourceAsStream(
						"configurazione.properties"));
				_utente = prop.getProperty("utente");
				_password = prop.getProperty("password");
			} catch (IOException e) {
			}
			Sessions.getCurrent().setAttribute("_utente", _utente);
			Sessions.getCurrent().setAttribute("_password", _password);

			Map properties = new HashMap();
			String database = "pico";
			properties.put(PersistenceUnitProperties.JDBC_URL,
					"jdbc:postgresql://localhost:5432/" + database.trim());
			properties.put(PersistenceUnitProperties.JDBC_USER, _utente);
			properties.put(PersistenceUnitProperties.JDBC_PASSWORD, _password);
			properties.put(PersistenceUnitProperties.SESSION_NAME, database);
			emf = Persistence.createEntityManagerFactory("pico", properties);
		}

		return emf;
	}

	public void setEmf(EntityManagerFactory emf) {
		this.emf = emf;
	}

	public EntityManager getEntityManager() {

		emf = getEmf();
		EntityManager em = emf.createEntityManager();

		return em;
	}

}